package com.yh.user.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.yh.user.entity.User;
import com.yh.user.pager.PageBean;
import com.yh.user.service.UserService;

public class UserAction extends ActionSupport implements ModelDriven<User> {
	private UserService userService = new UserService();
	private User user=new User();

	@Override
	public User getModel() {
		return user;
	}
	
	private int getPc(HttpServletRequest request){
		int pc=1;
		String param=request.getParameter("pc");
		if(param!=null&&!param.isEmpty()){
			try {
				pc=Integer.parseInt(param);
			} catch (RuntimeException e) {
				
			}
			
		}
		return pc;
	}
	
	private String getUrl(HttpServletRequest request){
		String url=request.getRequestURI();
		if(request.getQueryString()!=null){
			url+=request.getQueryString();
		}
		
		int index=url.lastIndexOf("pc=");
		if(index!=-1){
			url=url.substring(0,index);
		}
		return url;
	}

	/**
	 * 查询所有人信息
	 * 
	 * @return
	 */
	public String findAllUser() {
		HttpServletRequest request=ServletActionContext.getRequest();

		int pc=getPc(request);
		
		int ps=5;
		String url=getUrl(request);
		
		
		PageBean<User> pb=new PageBean<User>();
		
		
		pb.setPs(ps);
		
		pb.setPc(pc);
		pb.setPa((pc-1)*ps);
//		System.out.println("pa"+pb.getPa());
//		System.out.println("pc"+pb.getPc());
//		System.out.println("ps"+pb.getPs());

		pb.setUrl(url);
		List<User> list = userService.findAll(pb);
		pb.setTr(userService.countUser());

		pb.setBeanList(list);
				request.setAttribute("listUser", pb);
				

		return "success";
	}

	/**
	 * 删除用户信息
	 * 
	 * @return
	 * @throws IOException 
	 */
	public void deleteUser() throws IOException {
	//System.out.println(user.getId());
		userService.deleteUser(user);
		//HttpServletResponse resp = ServletActionContext.getResponse();
		
		
		
		
		
		//resp.getWriter().print(JSON.toJSONString(ss));
		
		//response.getWriter().print(json);

		
		
		//return "success";
	}
	/**
	 * 编辑
	 * @return
	 */
	public String editUser() {
		
		user=userService.findUserId(user);
		
		ServletActionContext.getRequest().setAttribute("user", user);
		

		return "success";
	}
	/**
	 * 更新
	 * @return
	 */
	public String updateUser() {
		userService.updateUser(user);
		return "success";
	}
	
	public String insertUser() {
		userService.insertUser(user);
		return "success";
	}


	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		return super.execute();
	}

}
